package soar.template.springboot.syncbuffer.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class UpdateService extends BaseService
{
    private final static Logger logger = LoggerFactory
            .getLogger(UpdateService.class);

    public UpdateResponse run(UpdateRequest request)
    {
        String login;
        try
        {
            // login = Optional.ofNullable(request.getLogin()).map(String::trim)
            // .orElse("");
            // if (login.isEmpty())
            // {
            // throw new Exception(String.format("login(%s) invalid", login));
            // }
        }
        catch (Exception e)
        {
            logger.error("request invalid");
            return create_response(9999, "参数错误");
        }

        EntityManager main_em = null;

        try
        {
            main_em = mainEntityManagerFactory.createEntityManager();

            main_em.getTransaction().begin();

            main_em.getTransaction().commit();

            UpdateResponse response = create_response(0, "成功");

            return response;
        }
        catch (Exception e)
        {
            if (e.getMessage() != null)
                logger.error("fail: {}", e);
            try
            {
                if (main_em != null && main_em.getTransaction().isActive())
                    main_em.getTransaction().rollback();
            }
            catch (Exception er)
            {
                logger.error("rollback fail: {}", er);
            }
            return create_response(9999, e.getMessage());
        }
        finally
        {
            if (main_em != null)
                main_em.close();
        }

    }

    private UpdateResponse create_response(int errno, String errmsg)
    {
        return new UpdateResponse(errno, errmsg);
    }
}
